<template>
  <Dialog v-model="dialogVisible" title="车辆维保管理导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :data="uploadData"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <!-- <div class="el-upload__tip">
            <el-checkbox v-model="updateSupport" />
            是否覆盖已经存在的数据
          </div> -->
          <span>仅允许导入 xls、xlsx 格式文件。</span>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { getAccessToken, getTenantId } from '@/utils/auth'
import type { UploadProps, UploadRawFile } from 'element-plus'
import { ElForm } from 'element-plus'

defineOptions({ name: 'VehiclesMaintenanceImportForm' })
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formRef = ref<InstanceType<typeof ElForm>>()
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref<InstanceType<typeof ElUpload>>()

// 表单数据
const form = reactive({
  date: ''
})

const importUrl =
  import.meta.env.VITE_BASE_URL +
  import.meta.env.VITE_API_URL +
  '/pplan/vehicles-maintenance/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref<UploadProps['fileList']>([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  updateSupport.value = 0
  fileList.value = []
  // 重置表单
  formRef.value?.clearValidate()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 上传时携带的数据
const uploadData = reactive({
  get updateSupport() {
    return updateSupport.value
  }
})

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length === 0) {
    message.error('请上传文件')
    return false
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 - 只显示成功和失败的数量汇总 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  formLoading.value = false
  dialogVisible.value = false // 无论结果如何，都关闭弹窗

  if (response.code !== 0) {
    // 如果后端返回了全局错误码（如认证失败、文件太大等），直接显示
    message.error(response.msg || '文件处理失败，请联系管理员。')
    return
  }

  const importResult = response.data || {}
  let totalSuccess = 0
  let totalFailure = 0

  // 遍历所有Sheet，统计成功和失败的总数
  if (importResult.sheetImportInfos && Object.keys(importResult.sheetImportInfos).length > 0) {
    Object.values(importResult.sheetImportInfos).forEach((sheetInfo) => {
      // 累加成功数量
      totalSuccess += sheetInfo.successCount || 0

      // 累加失败数量 (failureReasons 的键值对数量就是失败的行数)
      totalFailure += sheetInfo.failureReasons ? Object.keys(sheetInfo.failureReasons).length : 0
    })
  }

  // 显示汇总信息
  message.success(`导入完成：成功 ${totalSuccess} 条，失败 ${totalFailure} 条`)

  // 通知父组件刷新数据
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (err: any): void => {
  message.error('上传请求发生网络错误，请检查网络连接或联系管理员。')
  formLoading.value = false
  dialogVisible.value = false
}

/** 文件数超出提示 */
const handleExceed = (files: UploadRawFile[], uploadFiles: UploadRawFile[]) => {
  message.error('最多只能上传一个文件！')
}
</script>